package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.ModelAdapter;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.ModelSort;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.CharacterParser;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.PinyinModelComparator;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.ClearEditText;
import com.dotstone.chipism.view.SideBar;
import com.dotstone.chipism.view.SideBar.OnTouchingLetterChangedListener;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.tiqiaa.client.IRemoteClient;
import com.tiqiaa.client.IRemoteClient.CallBackOnRemoteDownloaded;
import com.tiqiaa.client.IRemoteClient.CallbackOnSearchDone;
import com.tiqiaa.client.impl.RemoteClient;
import com.tiqiaa.icontrol.util.LanguageUtils;
import com.tiqiaa.remote.IRemoteManager;
import com.tiqiaa.remote.entity.Page;
import com.tiqiaa.remote.entity.Remote;
import com.tiqiaa.remote.impl.RemoteManager;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ModelSelectionActivity extends BaseActivity implements CallbackOnSearchDone {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private TextView mTitleTv;
	private long brandId;
	private String brand;
	private int type;
	private String appliance;
	private List<Remote> rs = new ArrayList<Remote>();
	private List<ModelSort> modelSorts = new ArrayList<ModelSort>();
	private ListView mModelLv;
//	private RemoteClient rc;
	private Page page;
	private ModelAdapter modelAdapter;
	private SVProgressHUD mSVProgressHUD;
	private IRemoteClient client;
	private ModelSelectionActivity modelSelectionActivity;
	private CharacterParser characterParser;
	private SideBar sideBar;
	private ClearEditText mClearEditText;
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinModelComparator pinyinComparator;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_model_selection;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		modelSelectionActivity = this;
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mModelLv = $(R.id.model_lv);
		mTitleTv.setVisibility(View.VISIBLE);
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinModelComparator();
		type = getIntent().getIntExtra("type", 999);
		brand = getIntent().getStringExtra("brand");
		brandId = getIntent().getLongExtra("brandId", 999);
		appliance = Util.getAppliance(getApplicationContext(), type);
		mTitleTv.setText(brand + ": 型号 选择");
		client = new RemoteClient(ModelSelectionActivity.this);
		initModel();
		boolVersion();
		sideBar = (SideBar) findViewById(R.id.sidrbar);
		mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);
		mBackL.setOnClickListener(this);
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = modelAdapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					mModelLv.setSelection(position);
				}

			}
		});
		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		mModelLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int p, long arg3) {
				// TODO Auto-generated method stub
				// Remote r = rs.get(p);
				ModelSort m = modelAdapter.getAdapterData().get(p);
				Log.i("wmy", type + "点击了 = " + m.getRemoteId());
				boolean e = DeviceManager.getInstance().checkName(appliance + " " + brand + " " + m.getModel());
				if (e) {
					// 该名字的遥控器已经存在
					ToastShow.Show(getApplicationContext(), "已添加该型号遥控器");
					return;
				}
				// 将该遥控器下载 保存在本地后 跳转至遥控器界面
				client.download_reomte(m.getRemoteId(), new CallBackOnRemoteDownloaded() {
					@Override
					public void onRemoteDownloaded(int errcode, final Remote remote) {
						if (errcode != CallBackOnRemoteDownloaded.ERROR_CODE_SUCCESS) {
							Toast.makeText(getApplicationContext(), "下载遥控器失败。。。", Toast.LENGTH_SHORT).show();
							return;
						}
						IRemoteManager manager = new RemoteManager();
						manager.addRemote(remote);
						switch (type) {
						case DeviceType.DEVICE_TYPE_AIR_CONTROLLER:
							Intent intent1 = new Intent(getApplicationContext(), AddAirActivity1.class);
							// Intent intent1 = new
							// Intent(getApplicationContext(),
							// AddAirActivity2.class);
							intent1.putExtra("type", type);
							intent1.putExtra("appliance", appliance);
							intent1.putExtra("brand", brand);
							intent1.putExtra(RemoteActivity.INTENT_PARAMS_REMOTE_JSON, remote.getId());
							intent1.putExtra("model", remote.getModel());
							intent1.putExtra("remoteId", remote.getId());
							startActivity(intent1);
							break;
						case DeviceType.DEVICE_TYPE_FAN:
							Intent intent2 = new Intent(getApplicationContext(), AddFanActivity.class);
							intent2.putExtra("type", type);
							intent2.putExtra("appliance", appliance);
							intent2.putExtra("brand", brand);
							intent2.putExtra("model", remote.getModel());
							intent2.putExtra("remoteId", remote.getId());
							startActivity(intent2);
							break;
						case DeviceType.DEVICE_TYPE_TV:
							Intent intent3 = new Intent(getApplicationContext(), AddTvActivity.class);
							intent3.putExtra("type", type);
							intent3.putExtra("appliance", appliance);
							intent3.putExtra("brand", brand);
							intent3.putExtra("model", remote.getModel());
							intent3.putExtra("remoteId", remote.getId());
							startActivity(intent3);
							break;
						case DeviceType.DEVICE_TYPE_SATELLITE:
							Intent intent4 = new Intent(getApplicationContext(), RemoteSatelliteActivity.class);
							intent4.putExtra("type", type);
							intent4.putExtra("appliance", appliance);
							intent4.putExtra("brand", brand);
							intent4.putExtra("model", remote.getModel());
							intent4.putExtra("remoteId", remote.getId());
							startActivity(intent4);
							break;
						case DeviceType.DEVICE_TYPE_PROJECTOR:
							Intent intent5 = new Intent(getApplicationContext(), AddProjectorActivity.class);
							intent5.putExtra("type", type);
							intent5.putExtra("appliance", appliance);
							intent5.putExtra("brand", brand);
							intent5.putExtra("model", remote.getModel());
							intent5.putExtra("remoteId", remote.getId());
							startActivity(intent5);
							break;
						case DeviceType.DEVICE_TYPE_AUDIO:
							Intent intent7 = new Intent(getApplicationContext(), RemoteAudioActivity.class);
							intent7.putExtra("type", type);
							intent7.putExtra("appliance", appliance);
							intent7.putExtra("brand", brand);
							intent7.putExtra("model", remote.getModel());
							intent7.putExtra("remoteId", remote.getId());
							startActivity(intent7);
							break;
						case DeviceType.DEVICE_TYPE_BOX:
							Intent intent8 = new Intent(getApplicationContext(), AddBoxActivity.class);
							intent8.putExtra("type", type);
							intent8.putExtra("appliance", appliance);
							intent8.putExtra("brand", brand);
							intent8.putExtra("model", remote.getModel());
							intent8.putExtra("remoteId", remote.getId());
							startActivity(intent8);
							break;
						case DeviceType.DEVICE_TYPE_CAMERA:
							Intent intent9 = new Intent(getApplicationContext(), RemoteCameraActivity.class);
							intent9.putExtra("type", type);
							intent9.putExtra("appliance", appliance);
							intent9.putExtra("brand", brand);
							intent9.putExtra("model", remote.getModel());
							intent9.putExtra("remoteId", remote.getId());
							startActivity(intent9);
							break;
						case DeviceType.DEVICE_TYPE_DVD:
							Intent intent11 = new Intent(getApplicationContext(), AddDvdActivity.class);
							intent11.putExtra("type", type);
							intent11.putExtra("appliance", appliance);
							intent11.putExtra("brand", brand);
							intent11.putExtra("model", remote.getModel());
							intent11.putExtra("remoteId", remote.getId());
							startActivity(intent11);
							break;
						case DeviceType.DEVICE_TYPE_DENG:
							Intent intent13 = new Intent(getApplicationContext(), RemoteRGBLightActivity.class);
							intent13.putExtra("type", type);
							intent13.putExtra("appliance", appliance);
							intent13.putExtra("brand", brand);
							intent13.putExtra("model", remote.getModel());
							intent13.putExtra("remoteId", remote.getId());
							startActivity(intent13);
							break;

						default:
							break;
						}
					}
				});
			}
		});
	}
	
	private void filterData(String filterStr) {
		Log.i("wmy", "过滤字段 = "+filterStr);
		List<ModelSort> filterDateList = new ArrayList<ModelSort>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = modelSorts;
		} else {
			filterDateList.clear();
			for (ModelSort sortModel : modelSorts) {
				String name = sortModel.getModel();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}
		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		Log.i("wmy", "filterDateList.size() = "+filterDateList.size());
		modelAdapter.updateListView(filterDateList);
	}


	private void initModel() {
		// rc = new RemoteClient(getApplicationContext());
		// 显示加载进度条
		mSVProgressHUD = new SVProgressHUD(this);
		mSVProgressHUD.showWithStatus("正在加载");
		page = new Page();
		page.setPage(0);
		page.setAppliance_type(type);
		page.setBrand_id(brandId);
		page.setKeyword("");
		page.setLang(LanguageUtils.getLang());
		Log.i("wmy", "LanguageUtils.getLang() = " + LanguageUtils.getLang());
		// modelAdapter.clearRemotes();
		Log.e("wmy", "Locale.getDefault().toString() = " + Locale.getDefault().toString());
		search(page);
	}

	private void search(Page page) {
		// 通讯客户端
		IRemoteClient client = new RemoteClient(getApplicationContext());
		client.searchOfficial(page, this);
		// client.autoMatchRemotes(page, this);
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void onSearchDone(int errcode, List<Remote> remotes) {
		// TODO Auto-generated method stub
		if (errcode == CallbackOnSearchDone.ERROR_CODE_FAILURE) {
			showToast("搜索失败");
		} else {
			if (remotes != null && remotes.size() > 0) {

				for (Remote r : remotes) {
					Log.e("wmy", "搜索到型号:" + " " + r.getModel() + " " + r.getKeys().size());
					rs.add(r);
				}
				// 当前搜索的页数再加一页 重新搜索
				page.setPage(page.getPage() + 1);
				search(page);
				Log.e("wmy", "换页" + page.getPage());
			} else {
				// showToast("无更多遥控器");
				// 取消进度条显示
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				// 将获取的遥控器放入适配器展示
				// for(int i = 0;i<rs.size();i++){
				// ModelSort modelSort = new ModelSort();
				// modelSort.setModel(rs.get(i).getModel());
				// modelSort.setRemoteId(rs.get(i).getId());
				// modelSorts.add(modelSort);
				// }
				for (int i = 0; i < rs.size(); i++) {
					Remote b = rs.get(i);
					ModelSort bsort = new ModelSort();
					bsort.setModel(b.getModel());
					if (b.getModel() != null) {
						String pinyin = characterParser.getSelling(b.getModel());
						if (pinyin.length() < 2) {
							bsort.setSortLetters("#");
						} else {
							String sortString = pinyin.substring(0, 1).toUpperCase();
							if (sortString.matches("[A-Z]")) {
								bsort.setSortLetters(sortString.toUpperCase());
							} else {
								bsort.setSortLetters("#");
							}
						}
					} else {
						bsort.setSortLetters("#");
					}
					bsort.setRemoteId(b.getId());
					modelSorts.add(bsort);
				}
				Collections.sort(modelSorts, pinyinComparator);
				modelAdapter = new ModelAdapter(getApplicationContext(), modelSorts, brand, type);
				mModelLv.setAdapter(modelAdapter);
			}
		}
	}

}
